# Copyright (c) 2009 Daropia Project (www.daropia.org)
#
# This file is part of Daropia and is available under the terms
# of the GNU General Public Licence version 2.0 or later.


# Represent an user account

class User < Sequel::Model
    # Each user can post many messages
    one_to_many :posts
    
    # Eaxh user owns one to many characters
    one_to_many :characters

    # Temporary hold password in clear during user creation
    attr_accessor :password
    attr_accessor :password_confirmation

    # Encrypt the previous two attributes in the database
    # at the end of the user creation process
    def after_create
        self.encrypted_password = encrypt(password)
        @new = false
        save
    end

    # Check if the specified password is valid for the user
    def authenticated?(password)
        encrypted_password == encrypt(password)
    end

    # Encrypt password
    def encrypt(password)
        Digest::SHA1.hexdigest("--#{salt}--#{password}--")
    end

    # Used by Ramaze to check if an user is logged in
    def self.authenticate(hash)
        login, pass = hash['login'], hash['password']
        user = User[:login => login]

        if user && user.authenticated?(pass)
            return user
        else
            return nil
        end
    end

end
